package com.xac.aas.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;

import com.xac.R;
import com.xac.aas.logic.LoginFlowManager;
import com.xac.aas.model.UserInfo;
import com.xac.biz.friend.ui.FriendActivity;

public class LoginActivity extends Activity {
	private CheckBox saveUsername = null;
	private CheckBox savePassword = null;
	private Button loginButton = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		saveUsername = (CheckBox) findViewById(R.id.saveUsername);
		savePassword = (CheckBox) findViewById(R.id.savePassword);
		savePassword
				.setOnCheckedChangeListener(new SavePasswordCheckedChangeListener());
		loginButton = (Button) findViewById(R.id.loginButton);
		loginButton.setOnClickListener(new LoginOnClickListener());
		Log.d("LoginActivity", "LoginActivity:onCreate incoked!");
	}

	/**
	 * Save password listener, when select the save password checkbox, should make the 
	 * save username checkbox select too.
	 */
	class SavePasswordCheckedChangeListener implements OnCheckedChangeListener {

		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			if (isChecked) {
				saveUsername.setChecked(true);
			} else {
				saveUsername.setChecked(false);
			}
		}
	}
	
	/**
	 * login listener.
	 * @author daisongwan
	 *
	 */
	class LoginOnClickListener implements OnClickListener {
		@Override
		public void onClick(View view) {
			Log.d("LoginOnClickListener", "onClick invoked");
			EditText username = (EditText) findViewById(R.id.usernameText);
			EditText password = (EditText) findViewById(R.id.passwordText);
			EditText loginServerIP = (EditText) findViewById(R.id.loginServerIPText);
			EditText loginServerPort = (EditText) findViewById(R.id.loginServerPortText);
			
			UserInfo userInfo = new UserInfo();
			userInfo.setUsername(username.getText().toString());
			userInfo.setPassword(password.getText().toString());
			userInfo.setLoginServerIP(loginServerIP.getText().toString());
			userInfo.setLoginServerPort(Integer.parseInt(loginServerPort.getText().toString()));
			boolean loginResult = LoginFlowManager.getInstance().login(userInfo);
			if(loginResult){
				Intent intent = new Intent(LoginActivity.this, FriendActivity.class);
				startActivity(intent);
				finish();
			}
		}
		
	}
}